using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.GamePlay;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 实体跟随玩家
    /// args1：1:跟随的实体tag(0表示自己)，2：1开始跟随，0停止跟随，3：停止时是否设置rotationY，4：rotationY
    /// args2：1停止跟随后的目标点x，2：y，3：z。(可不填)
    /// </summary>
    public class ExecFollowHero : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamFollowHero;
            if (!config.tagOrMcid.TryGetValue(triggerEntity, out int tagOrMcid))
            {
                LogicLog.LogError("无法获取到tagOrMcid.");
                return;
            }
            bool isFollow = config.isFollow;
            bool isSetRotation = config.isSetRotation;
            int stopRotationY = config.stopRotationY;

            bool headToPosAfterStop = config.pos != Vector3Int.zero;
            int x = config.pos.x;
            int y = config.pos.y;
            int z = config.pos.z;

            LevelEntity entity;
            if (tagOrMcid == 0)
            {
                entity = triggerEntity;
            }
            else
            {
                entity = triggerEntity.region.GetEntityByTagOrMcid(tagOrMcid);
            }

            if (entity == null)
            {
                LogicLog.LogError($"没有找到Entity。tagOrMcid:{tagOrMcid}");
                return;
            }

            if (isFollow)
            {
                if (player.entityFollowingMe == entity)
                {
                    LogicLog.Log("实体已经在跟随该玩家。");
                    return;
                }

                //停止上一个跟随的玩家
                StopEntityFollowAnyPlayer(region, entity);

                entity.FollowHero(player);
            }
            else
            {
                StopEntityFollowAnyPlayer(region, entity);
                if (headToPosAfterStop)
                {
                    if (!isSetRotation)
                    {
                        entity.StartNavigation(new Vector3Logic(x, y, z), true);
                    }
                    else
                    {
                        entity.StartNavigation(new Vector3Logic(x, y, z), true, entity.moveSpeed, stopRotationY);
                    }
                }
                else if (isSetRotation)
                {
                    entity.SetRotationY(stopRotationY, true);
                }
            }
        }

        private void StopEntityFollowAnyPlayer(LevelRegion region, LevelEntity entity)
        {
            //停止上一个跟随的玩家
            foreach (var p in region.players)
            {
                if (entity == p.entityFollowingMe)
                {
                    entity.StopFollow(p);
                    break;
                }
            }
        }
    }
}
